// 创建 用户信息 小仓库
import { defineStore } from "pinia";
import type { UserState } from "./types/type";
import { reqLogin, reqUserInfo, reqLogout } from "@/api/user";
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from "@/utils/token";
import type {
  loginFormData,
  loginResponseData,
  userInfoResponseData,
} from "@/api/user/type";

let useUserStore = defineStore("User", {
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
      username: "",
      avatar: "",
    };
  },
  actions: {
    // 用户登录
    async userLogin(data: loginFormData) {
      let res: loginResponseData = await reqLogin(data);
      if (res.code == 200) {
        // 请求成功
        this.token = res.data as string;
        // 本地存储
        SET_TOKEN(res.data as string);
        return "ok";
      } else {
        // 请求失败：返回一个失败的promise状态
        return Promise.reject(new Error(res.data as string));
      }
    },
    async getUserInfo() {
      let res: userInfoResponseData = await reqUserInfo();
      if (res.code == 200) {
        this.username = res.data.name;
        this.avatar = res.data.avatar;
        return "ok";
      } else {
        return Promise.reject(new Error(res.message));
      }
    },
    async signOut() {
      // 登出逻辑：1、请求登出接口，2、清空本地存储的用户信息，3、跳转到登录页面
      let res: any = await reqLogout();
      if (res.code == 200) {
        this.token = "";
        this.username = "";
        this.avatar = "";
        REMOVE_TOKEN();
        return "ok";
      } else {
        return Promise.reject(new Error(res.message));
      }
    },
  },
  getters: {},
});

// 对外暴露小仓库
export default useUserStore;
